﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Windows.Forms;

namespace XYZCompiler
{
    public partial class MainView : Form
    {
        public bool LineChange = false;
        public int line = 0;
        public MainView()
        {
            InitializeComponent();
            _flowController.Reset();
            _flowController.CompileStateChanged += _flowController_CompileStateChanged;
            _errorDataGrid.Columns.Add("Description");
            _errorDataGrid.Columns.Add("Row");
            _errorDataGrid.Columns.Add("Column");
            ErrorGridView.DataSource = _errorDataGrid;
            _flowController.Error += ErrorHandler;
        }
        DataTable _errorDataGrid = new DataTable();

        void _flowController_CompileStateChanged(FlowController.CompileState s)
        {
            this.state.Text = s.ToString();
            if (s == FlowController.CompileState.READY)
            {
                sourceCodeTextBox.ReadOnly = false;
            }
            else if (s == FlowController.CompileState.ERROR)
            {
                //MessageBox.Show("Error! ");
                _flowController.Reset();
            }
            else
                sourceCodeTextBox.ReadOnly = true;
        }

        private FlowController _flowController = new FlowController();

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileDlg = new OpenFileDialog();
            using (fileDlg)
            {
                DialogResult dialogResult = fileDlg.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    var streamReader = new StreamReader(fileDlg.OpenFile());
                    sourceCodeTextBox.Text = streamReader.ReadToEnd();
                    openedFileName = fileDlg.FileName;
                    streamReader.Close();
                }
            }
           
        }

        private string openedFileName = "";

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sourceCodeTextBox.Text = "";
            openedFileName = "";
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openedFileName == "")
            {
                var fileDlg = new OpenFileDialog();
                using (fileDlg)
                {
                    fileDlg.CheckFileExists = false;
                    DialogResult dialogResult = fileDlg.ShowDialog();
                    if (dialogResult == DialogResult.OK)
                    {
                        openedFileName = fileDlg.FileName;
                    }
                    else
                        return;
                }
            }
            var stream = new FileStream(openedFileName, FileMode.Create);
            if (stream == null)
            {
                System.Windows.Forms.MessageBox.Show("Can't save file!");
                return;
            }
            var streamWrite = new StreamWriter(stream);
            streamWrite.Write(sourceCodeTextBox.Text);
            streamWrite.Close();
        }

        private void MainView_Load(object sender, EventArgs e)
        {
            CompilerHelper.OutPutBox = consoleTextBox;
            CompilerHelper.SourceTextBox = sourceCodeTextBox;
            this.LostFocus += new EventHandler(MainView_LostFocus);

        }

        void MainView_LostFocus(object sender, EventArgs e)
        {
            this.Focus();
        }

        private void LexerButton_Click(object sender, EventArgs e)
        {
            if (_flowController.State == FlowController.CompileState.READY)
            {
                ClearError();
                _flowController.Source = this.sourceCodeTextBox.Text;
            }
            _flowController.NextStaget();
        }

        private void Reset_Click(object sender, EventArgs e)
        {
            ClearError();
            _flowController.Reset();
        }

        void ErrorHandler(string s, int c, int r)
        {
            var row = _errorDataGrid.NewRow();
            row["Description"] = s;
            row["Row"] = r.ToString();
            row["Column"] = c.ToString();
            _errorDataGrid.Rows.Add(row);
        }

        void ClearError()
        {
            this.consoleTextBox.Text = "";
            this._errorDataGrid.Rows.Clear();
        }

        private void ShowResultButton_Click(object sender, EventArgs e)
        {
            CompilerHelper.ShowResultDialog(_flowController.State,_flowController.CurrentStageResult);
        }

        private void ErrorGridView_Click(object sender, EventArgs e)
        {
            if (ErrorGridView.SelectedRows.Count > 0)
            {
                var r = ErrorGridView.SelectedRows[0].Cells["Row"];
                var c = ErrorGridView.SelectedRows[0].Cells["Column"];
                CompilerHelper.SelectWord(int.Parse(r.Value.ToString()), int.Parse(c.Value.ToString()));
            }
        }

        private void MainView_Activated(object sender, EventArgs e)
        {
            if(LineChange)
            {
                if (line < 1)
                    return;
                var SourceTextBox = sourceCodeTextBox;
                var start = SourceTextBox.GetFirstCharIndexFromLine(line - 1);
                var end = SourceTextBox.GetFirstCharIndexFromLine(line);
                SourceTextBox.SelectionStart = start;
                SourceTextBox.SelectionLength = end - start - 1;
                SourceTextBox.Focus();
                LineChange = false;
            }
        }

    }
}
